package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.service.WmUserService;
import com.heima.wemedia.mapper.WmUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author 石头
 * @description 针对表【wm_user(自媒体用户信息表)】的数据库操作Service实现
 * @createDate 2022-06-13 16:16:14
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser>
        implements WmUserService {

    /**
     * 用户登录
     *
     * @param wmLoginDto
     * @return
     */
    @Override
    public ResponseResult login(WmLoginDto wmLoginDto) {
        String password = wmLoginDto.getPassword();
        String name = wmLoginDto.getName();
        // 校验账号是否获取到对象
        LambdaQueryWrapper<WmUser> queryWrapper = Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name);
        WmUser wmUser = this.getOne(queryWrapper);
        // 校验用户是否存在
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_NAME_ERROR);
        }

        // 校验密码
        String wmUserPassword = wmUser.getPassword();
        // 密码+盐
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + wmUser.getSalt()).getBytes());
        if (!wmUserPassword.equals(md5DigestAsHex)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 用户名和密码都正确，根据用户id生成token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));

        // 用户信息脱敏
        wmUser.setSalt("");
        wmUser.setPassword("");

        // 封装返回数据
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", wmUser);
        resultMap.put("token", token);

        return ResponseResult.okResult(resultMap);
    }
}




